package com.coffee.core;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import lombok.Getter;
import lombok.Setter;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: songkui
 * @since: 2022/3/10 16:56
 */
public class CoffeeHeader {

    public final static String HEADER_USERID = "User-id";
    public final static String HEADER_USERCODE = "User-code";
    public final static String HEADER_TOKEN = "Token";
    public final static String HEADER_TENANT = "Tenant";
    public final static String HEADER_VERSION = "V-No";
    public final static String HEADER_DAC = "DAC-ADM";

    private final static String ALL_HEADER = String.format("%s,%s,%s,%s,%s,%s", HEADER_USERID, HEADER_USERCODE, HEADER_TOKEN, HEADER_TENANT, HEADER_VERSION, HEADER_DAC);

    public static String getUserCode(HttpServletRequest request){
        return getHeader(request, HEADER_USERCODE);
    }

    public static Long getUserId(HttpServletRequest request){
        String userId = getHeader(request, HEADER_USERID);
        return NumberUtil.parseLong(userId);
    }

    public static UserInfo getUserInfo(HttpServletRequest request){
        String userCode = getUserCode(request);
        Long userId = getUserId(request);
        Long tenantId = getTenant(request);
        if (userId > 0){
            return new UserInfo(userCode, userId, tenantId);
        }
        return null;
    }

    public static String getToken(HttpServletRequest request){
        return getHeader(request, HEADER_TOKEN);
    }

    public static Long getTenant(HttpServletRequest request){
        String tenantId = getHeader(request, HEADER_TENANT);
        return NumberUtil.isNumber(tenantId) ? Long.valueOf(tenantId) : null;
    }

    public static String getVersion(HttpServletRequest request){
        return getHeader(request, HEADER_VERSION);
    }

    public static boolean isMochaHead(String head){
        if (StrUtil.isEmpty(head)){
            return false;
        }
        return ALL_HEADER.contains(head.trim()) ? true : false;
    }


    private static String getHeader(HttpServletRequest request, String name){
        try {
           return null == request ? null : request.getHeader(name);
        }catch (Exception e){
            return null;
        }
    }

    @Getter
    @Setter
    public static class UserInfo{
        private String userCode;
        private Long userId;
        private Long tenantId;
        public UserInfo(String userCode, Long userId, Long tenantId){
            this.userCode = userCode;
            this.userId = userId;
            this.tenantId = tenantId;
        }
    }
}
